#!/usr/bin/env python
# -*- coding:utf-8 -*-

import datetime
import math
import json

from sqlalchemy import or_

from app import db
from ..models.thingModel import Teacher
from ..utils import commons
from ..utils.response_code import RET, error_map_EN
from ..utils.loggings import loggings


class TeacherController(Teacher):

    # add
    @classmethod
    def add(cls, **kwargs):
        try:
            model = Teacher(
                thingID=kwargs.get('thingID'),
                name=kwargs.get('name'),
                describe=kwargs.get('describe'),
                addTime=kwargs.get('addTime'),
                
            )

            # 判断字段值是否有重复
            results = {
                'add_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'thingID': model.thingID,
                'name' : model.name,
                'describe' : model.describe
                
            }
            filter_list = [cls.thingID == kwargs.get('thingID')]
            res = db.session.query(cls).filter(or_(*filter_list)).all()
            db.session.add(model)
            db.session.commit()
            if len(res) > 0:
                return {'code': RET.DATAEXIST, 'message': error_map_EN[RET.DATAEXIST],
                        'data': {'error': '提交的(thingID)值有重复'}}
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # get
    @classmethod
    def get(cls, **kwargs):
        try:
            filter_list = [cls.isDelete == 0]
            if kwargs.get('thingID'):
                filter_list.append(cls.thingID == kwargs['thingID'])
            else:
                if kwargs.get('name'):
                    filter_list.append(cls.name == kwargs.get('name'))
                if kwargs.get('describe'):
                    filter_list.append(cls.describe == kwargs.get('describe'))
                if kwargs.get('addTime'):
                    filter_list.append(cls.addTime == kwargs.get('addTime'))
                

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))
            
            teacher_info = db.session.query(cls).filter(*filter_list)
            
            count = teacher_info.count()
            pages = math.ceil(count / size)
            teacher_info = teacher_info.limit(size).offset((page - 1) * size).all()
   
            results = commons.query_to_dict(teacher_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages, 'data': results}
            
        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # delete
    @classmethod
    def delete(cls, **kwargs):
        try:
            filter_list = [cls.isDelete == 0]
            if kwargs.get('thingID'):
                primary_key_list = []
                for primary_key in str(kwargs.get('thingID')).replace(' ', '').split(','):
                    primary_key_list.append(cls.thingID == primary_key)
                filter_list.append(or_(*primary_key_list))
                
            else:
                if kwargs.get('name'):
                    filter_list.append(cls.name == kwargs.get('name'))
                if kwargs.get('describe'):
                    filter_list.append(cls.describe == kwargs.get('describe'))
                if kwargs.get('addTime'):
                    filter_list.append(cls.addTime == kwargs.get('addTime'))
                
            res = db.session.query(cls).filter(*filter_list).with_for_update()

            results = {
                'delete_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'thingID': []
            }
            for query_model in res.all():
                results['thingID'].append(query_model.thingID)

            res.update({'isDelete': 1})
            db.session.commit()

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()
    
    # update
    @classmethod
    def update(cls, **kwargs):
        try:
            
            filter_list = [cls.isDelete == 0]
            filter_list.append(cls.thingID == kwargs.get('thingID'))
            
            res = db.session.query(cls).filter(*filter_list).with_for_update()

            results = {
                'update_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'thingID': res.first().thingID,
                
            }
            
            res.update(kwargs)
            db.session.commit()

            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # batch add
    @classmethod
    def add_list(cls, **kwargs):
        param_list = json.loads(kwargs.get('TeacherList'))
        model_list = []
        for param_dict in param_list:
            
            model = Teacher(
                thingID=param_dict.get('thingID'),
                name=param_dict.get('name'),
                describe=param_dict.get('describe'),
                addTime=param_dict.get('addTime'),
                
            )
            model_list.append(model)
        
        try:
            db.session.add_all(model_list)
            db.session.commit()
            results = {
                'added_records': [],
                'add_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            for model in model_list:
                added_record = {}
                added_record['thingID'] = model.thingID
                
                results['added_records'].append(added_record)
            
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}
            
        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()
